package com.hulk.sequence;

import com.hulk.sequence.annotation.EnableDbSeqConfig;
import com.hulk.sequence.builder.DbSeqBuilder;
import com.hulk.sequence.properties.SequenceDbProperties;
import com.hulk.sequence.range.impl.name.DefaultBizName;
import com.hulk.sequence.worker.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @author hulk
 * @date 2019-05-26
 */


@Configuration
@ConditionalOnMissingBean(Sequence.class)
@EnableConfigurationProperties(SequenceDbProperties.class)
@ConditionalOnBean(annotation = EnableDbSeqConfig.class)
public class DbSeqAutoConfiguration {


	@Autowired
	private SequenceDbProperties properties;

	/**
	 * 数据库作为发号器的存储介质
	 *
	 * @param dataSource
	 * @param properties
	 * @return
	 */
	@Bean
	@ConditionalOnBean(DataSource.class)
	@ConditionalOnProperty("xsequence.db")
	public Sequence dbSequence(DataSource dataSource) {
		return DbSeqBuilder
				.create()
				.bizName(new DefaultBizName(properties.getBizName()))
				.dataSource(dataSource)
				.step(properties.getStep())
				.retryTimes(properties.getRetryTimes())
				.tableName(properties.getTableName())
				.build();
	}


}